-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.


local log = require 'mc.logging'
local ini_parser = require 'mc.v2_persistence'

local parser_cfg = {}

local function cfg_new(name, data)
    local cfg = {
        name = name,
        component_id = tonumber(data.ComponentID),
        component_id_ex = tonumber(data.ComponentIDEx)
    }
    return cfg
end

-- prepare阶段框架会下发解包的update.cfg路径，解析文件内容，获取每个Firmware的配置
--- @param path string update.cfg文件路径
--- @return table 返回cfg文件的列表
function parser_cfg.get_cfgs(path)
    local cfgs = {}
    if not path then
        log:error("Cfg path is nil")
        return cfgs
    end

    log:info("get cfg path=%s", path)
    local data = ini_parser.load_file(path)
    if not data.Basic or not data.Basic.Version then
        log:error('Get Basic Version failed')
        return cfgs
    end
    local file_num = tonumber(data.Firmware.FileNum)
    if file_num == 0 then
        log:error('Update file num is invalid')
        return cfgs
    end
    for i = 1, file_num - 1 do -- 第1个Firmware指的就是配置文件，从1开始
        local name = 'Firmware' .. i
        if data[name] then
            cfgs[name] = cfg_new(name, data[name])
            log:info("Get Firmware, name=%s", name)
        end
    end
    return cfgs
end

--- @param file_path string 升级文件目录/dev/shm/upgrade/FirmwareX
--- @return string 目录
--- @return string 文件名
function parser_cfg.parse_dir(file_path)
    local s, e = string.find(file_path, "/.+/")
    local dir = string.sub(file_path, s, e)
    local firmware_name = string.sub(file_path, e + 1, -1)
    return dir, firmware_name
end

return parser_cfg